 package com.quanyan.place.service.impl;

 import com.quanyan.api.APIResponse;
import com.quanyan.common.Plugin.Page;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.enums.SysParameterConfigEnum;
import com.quanyan.place.entity.Dict;
import com.quanyan.place.entity.DictExample;
import com.quanyan.place.entity.TbCity;
import com.quanyan.place.entity.TbCityExample;
import com.quanyan.place.entity.TbCommonParameter;
import com.quanyan.place.entity.TbCommonParameterExample;
import com.quanyan.place.entity.TbProvince;
import com.quanyan.place.entity.TbProvinceExample;
import com.quanyan.place.entity.apireq.ReqCity;
import com.quanyan.place.entity.apireq.ReqKeyWords;
import com.quanyan.place.entity.vo.ReqBaseSearch;
import com.quanyan.place.mapper.DictMapper;
import com.quanyan.place.mapper.TbCityMapper;
import com.quanyan.place.mapper.TbCommonParameterMapper;
import com.quanyan.place.mapper.TbProvinceMapper;
import com.quanyan.place.service.BaseService;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by yangyun on 2016/5/20.
 */
@Service("baseService")
public class BaseServiceImpl implements BaseService {

    @Autowired
    private TbCityMapper cityMapper;

    @Autowired
    private TbProvinceMapper provinceMapper;

    @Autowired
    private TbCommonParameterMapper parameterMapper;

    @Autowired
    private DictMapper dictMapper;

    @Override
    public PageObj<List<TbCity>> getCityList(Integer provinceId, Integer pageNum, Integer pageSize, String keyWords) {
        TbCityExample example = new TbCityExample();
        TbCityExample.Criteria criterial = example.createCriteria();

        if (provinceId != null) {
            criterial.andProvinceIdEqualTo(provinceId);
        }
        if (StringUtils.isNotEmpty(keyWords)) {
            criterial.andNameLike("%" + keyWords + "%");
        }
        int totalNum = cityMapper.countByExample(example);
        example.setPage(new Page(pageNum * pageSize, pageSize, totalNum));
        List<TbCity> cityList = cityMapper.selectByExample(example);
        PageObj<List<TbCity>> result = PageObj.create(totalNum, pageNum, pageSize, cityList);
        return result;
    }



    /**
     * 获取系统参数列表
     * @param reqBaseSearch
     * @return
     */
    @Override
    public PageObj<List<TbCommonParameter>> getSysParameterList(ReqBaseSearch reqBaseSearch) {
        TbCommonParameterExample tbParamegerExample = new TbCommonParameterExample();
        TbCommonParameterExample.Criteria criteriaParameter = tbParamegerExample.createCriteria();
        criteriaParameter.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        Integer pageSize = Constants.DEFAULT_PAGE_SIZE;
        Integer pageNum = 0;  // 默认第一页
        if (null != reqBaseSearch){
            if (null != reqBaseSearch.getPageSize()){
                pageSize = reqBaseSearch.getPageSize();
            }
            if (StringUtils.isNotEmpty(reqBaseSearch.getKey())) {
                criteriaParameter.andNameLike("%" + reqBaseSearch.getKey() + "%");
            }
            if (null != reqBaseSearch.getPageNum()){
                pageNum = reqBaseSearch.getPageNum();
            }
        }
        int totalNum = parameterMapper.countByExample(tbParamegerExample);
        tbParamegerExample.setOrderByClause(" parameter_key, parameter_value ");
        tbParamegerExample.setPage(new Page(pageNum * pageSize, pageSize, totalNum));
        List<TbCommonParameter> records = parameterMapper.selectByExample(tbParamegerExample);
        PageObj<List<TbCommonParameter>> result = PageObj.create(totalNum, pageNum, pageSize, records);
        return result;
    }

    /**
     * 保存系统参数
     *
     * @param sysParameter
     * @return
     */
    public APIResponse saveOrUpdateSysParameter(TbCommonParameter sysParameter) {
        List<String> errMsg = new ArrayList<String>();
        if (sysParameter != null) {
            if (sysParameter.getId() == null) {
                sysParameter.setIsDelete(Constants.IS_DELETE_FALSE);
                sysParameter.setCreateTime(Calendar.getInstance().getTime());
                sysParameter.setUpdateTime(Calendar.getInstance().getTime());
                this.parameterMapper.insert(sysParameter);
            } else {
                TbCommonParameter dbParameter = parameterMapper.selectByPrimaryKey(sysParameter.getId());
                dbParameter.setName(sysParameter.getName());
                //dbParameter.setParameterKey(sysParameter.getParameterKey());
                //dbParameter.setCompanyId(sysParameter.getCompanyId());
                dbParameter.setParameterValue(sysParameter.getParameterValue());
                dbParameter.setExtendInfo(sysParameter.getExtendInfo());  // 扩展信息
                dbParameter.setIsEnable(sysParameter.getIsEnable());
                dbParameter.setUpdateTime(Calendar.getInstance().getTime());
                parameterMapper.updateByPrimaryKey(dbParameter);
            }
        }
        if (errMsg.size() > 0) {
            return APIResponse.returnFail(errMsg.toString());
        }
        return APIResponse.returnSuccess();
    }

    /**
     * 删除系统参数
     *
     * @param id
     * @return
     */
    public APIResponse sysParameterDelete(Integer id) {
        List<String> errMsg = new ArrayList<String>();
        if (id != null) {
            TbCommonParameter parameter = parameterMapper.selectByPrimaryKey(id);
            parameter.setIsDelete(Constants.IS_DELETE_TRUE);
            parameterMapper.updateByPrimaryKeySelective(parameter);
        }
        if (errMsg.size() > 0) {
            return APIResponse.returnFail(errMsg.toString());
        }
        return APIResponse.returnSuccess();
    }

    @Override
    public PageObj<List<TbProvince>> getProvinceList(Integer pageNum, Integer pageSize, String keyWords) {
        TbProvinceExample example = new TbProvinceExample();
        TbProvinceExample.Criteria criterial = example.createCriteria();
        if (StringUtils.isNotEmpty(keyWords)) {
            criterial.andNameLike("%" + keyWords + "%");
        }
        int totalNum = provinceMapper.countByExample(example);
        example.setPage(new Page(pageNum * pageSize, pageSize, totalNum));
        List<TbProvince> provinceList = provinceMapper.selectByExample(example);
        PageObj<List<TbProvince>> result = PageObj.create(totalNum, pageNum, pageSize, provinceList);
        return result;
    }

    /**
     * 取得参数配置的最大专题数量
     * @return
     */
    public Integer getConfigMaxSubjectNum() {
        TbCommonParameter parameter = this.getParameterByKey(SysParameterConfigEnum.CONFIG_MAX_SUBJECT_NUMBER.getCode());
        Integer maxSubjectNum = 0;
        if (parameter != null && parameter.getParameterValue() != null){
            maxSubjectNum = Integer.valueOf(parameter.getParameterValue());
        }
        return maxSubjectNum;
    }

    /**
     * 取得搜索类型开关 1；开启solr查询 2：直接查询数据库
     * @return
     */
    public Integer getPlaceSearchType() {
        TbCommonParameter parameter = this.getParameterByKey(SysParameterConfigEnum.CONFIG_PLACE_SEARCH_TYPE.getCode());
        Integer maxSubjectNum = 0;
        if (parameter != null && parameter.getParameterValue() != null){
            maxSubjectNum = Integer.valueOf(parameter.getParameterValue());
        }
        return maxSubjectNum;
    }

    /**
     * 取得GPS定位到用户位置与场馆位置距离
     * @return
     */
    public Double getPlaceRecommendArea() {
        TbCommonParameter parameter = this.getParameterByKey(SysParameterConfigEnum.PLACE_RECOMMEND_AREA.getCode());
        Double maxSubjectNum = 0d;
        if (parameter != null && parameter.getParameterValue() != null){
            maxSubjectNum = Double.valueOf(parameter.getParameterValue());
        }
        return maxSubjectNum;
    }

    /**
     * 获取订场订单限制规则
     * @return
     */
    public Map<String,String> getPlaceOrderRule(){
        Map<String,String> orderRuleMap = new HashMap<String,String>();
        List<TbCommonParameter> parameterList = getParameterListByKey(SysParameterConfigEnum.CONFIG_PLACE_ORDER_RULE.getCode(), false);
        if (CollectionUtils.isNotEmpty(parameterList)){
            for (TbCommonParameter parameter : parameterList){
                orderRuleMap.put(parameter.getParameterValue(),parameter.getExtendInfo());
            }
        }
        return orderRuleMap;
    }

    /**
     * 取得系统参数（单一）
     *
     * @param key
     * @return
     */
    public TbCommonParameter getParameterByKey(String key) {
        TbCommonParameterExample example = new TbCommonParameterExample();
        TbCommonParameterExample.Criteria criteria = example.createCriteria();
        criteria.andParameterKeyEqualTo(key).andIsDeleteEqualTo((byte)0);//0未删除
        
        List<TbCommonParameter> parameterList = parameterMapper.selectByExample(example);
        if (parameterList != null && parameterList.size() > 0) {
            return parameterList.get(0);
        } else {
            return null;
        }
    }

    /**
     * 取得系统参数（多个）
     *
     * @param key
     * @return
     */
    public List<TbCommonParameter> getParameterListByKey(String key, boolean filterDisabled) {
        TbCommonParameterExample example = new TbCommonParameterExample();
        TbCommonParameterExample.Criteria criteria = example.createCriteria();
        criteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        if (filterDisabled) {
            // 过滤掉已禁用的
            criteria.andIsEnableEqualTo(Constants.YES); // 启用状态
        }
        criteria.andParameterKeyEqualTo(key);
        List<TbCommonParameter> parameterList = parameterMapper.selectByExample(example);
        return parameterList;
    }

    /**
     * 根据城市Id获取城市
     * @param cityId
     * @return
     */
    public TbCity getCityById(Integer cityId){
        if (null != cityId){
            return cityMapper.selectByPrimaryKey(cityId);
        } else {
            return null;
        }
    }

    /**
     * 添加城市
     * @param reqCity
     * @return
     */
    public APIResponse saveCity(ReqCity reqCity) {

        TbCityExample tbCityExample = new TbCityExample();
        TbCityExample.Criteria criteria = tbCityExample.createCriteria();
        criteria.andNameEqualTo(reqCity.getName().trim());
        List<TbCity> list = cityMapper.selectByExample(tbCityExample);
        if (list.size()>0){
            return APIResponse.returnFail("城市添加失败，该城市以存在!");
        }
        TbCity tbCity = new TbCity();
        /*tbCity.setProvinceId(reqCity.getProvinceId());
        tbCity.setName(reqCity.getName());
        tbCity.setLat(reqCity.getLat());
        tbCity.setLng(reqCity.getLng());
        tbCity.setCityDesc(reqCity.getCityDesc());
        tbCity.setIsActive(reqCity.getIsActive());
        tbCity.setIsEnable(reqCity.getIsEnable());
        tbCity.setIsPublic(reqCity.getIsPublic());
        tbCity.setCreateTime(new Date());*/
        try {
            BeanUtils.copyProperties(tbCity,reqCity);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        tbCity.setCreateTime(new Date());
        cityMapper.insertSelective(tbCity);
        return APIResponse.returnSuccess("城市添加成功");
    }

    /**
     * 更新城市
     * @param reqCity
     * @return
     */
    public APIResponse updateCity(ReqCity reqCity){
        TbCity tbCity = new TbCity();
        try {
            BeanUtils.copyProperties(tbCity,reqCity);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        tbCity.setUpdateTime(new Date());
        cityMapper.updateByPrimaryKeySelective(tbCity);
        return APIResponse.returnSuccess("城市更新成功");
    }

    /**
     * 商家端获取省份列表（不分页）
     * @return
     */
    public List<TbProvince> getProvinceListAdmin() {
        TbProvinceExample example = new TbProvinceExample();
        List<TbProvince> provinceList = provinceMapper.selectByExample(example);
        return provinceList;
    }

    @Override
    public PageObj<List<Dict>> getDicts(ReqKeyWords req) {
        DictExample example = new DictExample();
        DictExample.Criteria criteria = example.createCriteria();
        criteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        if(StringUtils.isNoneEmpty(req.getKeyWords())){
            criteria.andTagGroupLike("%"+ req.getKeyWords() +"%");
        }
        int total = dictMapper.countByExample(example);
        example.setPage(new Page(req.getPageNum() * req.getPageSize(), req.getPageSize(), total));
        List<Dict> dicts = dictMapper.selectByExample(example);
        return PageObj.create(total, req.getPageNum(), req.getPageSize(), dicts);
    }

    @Override
    public void editDict(Dict dict) {
        Dict tbDict = new Dict();
        try{
            BeanUtils.copyProperties(tbDict,dict);
        }  catch (Exception e) {
            e.printStackTrace();
        }
        dictMapper.updateByPrimaryKeySelective(tbDict);
    }

    @Override
    public void deleteDict(int id) {
        Dict tbDict = new Dict();
        tbDict.setId(id);
        tbDict.setIsDelete(Constants.IS_DELETE_TRUE);
        dictMapper.updateByPrimaryKeySelective(tbDict);
    }

}
